package com.llyb.tingshu.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.llyb.tingshu.account.mapper.RechargeInfoMapper;
import com.llyb.tingshu.account.mapper.UserAccountDetailMapper;
import com.llyb.tingshu.account.mapper.UserAccountMapper;
import com.llyb.tingshu.account.service.RechargeInfoService;
import com.llyb.tingshu.account.service.UserAccountService;
import com.llyb.tingshu.common.constant.SystemConstant;
import com.llyb.tingshu.model.account.RechargeInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llyb.tingshu.vo.account.RechargeInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Autowired
	private UserAccountService userAccountService;

	@Override
	public RechargeInfo getRechargeInfoByOrderNo(String orderNo) {
		// 根据订单号查询对象
		return this.getOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo,orderNo));
	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {

		RechargeInfo rechargeInfo = new RechargeInfo();
		rechargeInfo.setUserId(userId);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);

		String orderNo = UUID.randomUUID().toString().replaceAll("-","");
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfoMapper.insert(rechargeInfo);
		return orderNo;
	}

	@Override
	public void rechargePaySuccess(String orderNo) {
		RechargeInfo rechargeInfo = this.getRechargeInfoByOrderNo(orderNo);

		if (rechargeInfo != null && SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
			rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
			rechargeInfoMapper.updateById(rechargeInfo);
		}

		// 添加 user_account
		userAccountMapper.addAccountAmount(rechargeInfo.getRechargeAmount(),rechargeInfo.getUserId());

		// 添加 user_account_detail
		userAccountService.addUserAccountDetail(rechargeInfo.getUserId(),"余额充值",
				SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,rechargeInfo.getRechargeAmount(),orderNo);
	}
}
